package com.teemor.im.remoting.netty;

import com.teemor.im.common.command.EventType;
import com.teemor.im.common.command.RemoteCommand;
import com.teemor.im.executor.CommandDispatcher;
import com.teemor.im.executor.CommandTask;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 命令分发handler
 *
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/16 10:59
 */
@Slf4j
public class CommandDispatcherHandler extends SimpleChannelInboundHandler<RemoteCommand> {

    protected final Map<String, ResponseFuture> responseMap;

    public CommandDispatcherHandler(Map<String, ResponseFuture> responseMap) {
        super();
        this.responseMap = responseMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RemoteCommand msg) {
        log.info("远程通信,msg: {}", msg.toString());
        wrapperTask(ctx, msg, responseMap.get(msg.getCommandId()));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接建立成功");
        RemoteCommand message = new RemoteCommand();
        message.setEventType(EventType.PING);
        ctx.writeAndFlush(message);
    }

    private void wrapperTask(ChannelHandlerContext ctx, RemoteCommand command, ResponseFuture responseFuture) {
        CommandTask commandTask = new CommandTask(command, command.getEventType(), responseFuture);
        commandTask.setCtx(ctx);
        CommandDispatcher.doDispatcher(commandTask);
    }

}
